package org.luxor.commons.mqtt.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.luxor.commons.mqtt.config.properties.MqttClientProperties;
import org.luxor.commons.mqtt.exception.MqttClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.Assert;

/**
 * Mqtt自动配置
 *
 * @author Mr.Yan  @date: 2024/08/09
 */
@Configuration
@Import(MqttTopicListenerRegistrar.class)
@EnableConfigurationProperties(MqttClientProperties.class)
@ConditionalOnProperty(prefix = MqttClientProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class MqttAutoConfig {
    private static final Logger log = LoggerFactory.getLogger(MqttAutoConfig.class);

    @Bean
    public MqttClient client(MqttClientProperties mqttClientProperties) throws MqttClientException {
        try {
            log.info("Initialize the instantiation of MqttClient...");

            Assert.hasText(mqttClientProperties.getServerUri(), "Environment[spring.mqtt.server-uri] is null");
            Assert.hasText(mqttClientProperties.getClientId(), "Environment[spring.mqtt.client-id] is null");

            MqttClient client = new MqttClient(mqttClientProperties.getServerUri(), mqttClientProperties.getClientId(), new MemoryPersistence());
            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(mqttClientProperties.getUsername());
            connOpts.setPassword(mqttClientProperties.getPassword().toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);
            // 建立连接
            client.connect(connOpts);
            log.info("Initialize the instantiation of MqttClient, complete");
            return client;
        } catch (Exception e) {
            throw new MqttClientException("Initialize the instantiation of MqttClient, fail", e);
        }
    }

}
